import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'
import type { BlogPost, BlogStats } from './BlogTypes'

// 配置 marked 使用 highlight.js 进行代码高亮
const renderer = new marked.Renderer()

// 重写代码块渲染方法
renderer.code = function({ text, lang, escaped }: { text: string; lang?: string; escaped?: boolean }) {
  const validLang = !!(lang && hljs.getLanguage(lang))
  const highlighted = validLang
    ? hljs.highlight(text, { language: lang! }).value
    : hljs.highlightAuto(text).value
  
  return `<pre><code class="hljs language-${lang || 'text'}">${highlighted}</code></pre>`
}

marked.setOptions({
  renderer: renderer
})

// 解析 Front Matter
export function parseFrontMatter(content: string): {
  frontMatter: Record<string, any>
  markdown: string
} {
  const frontMatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/
  const match = content.match(frontMatterRegex)
  
  if (!match) {
    return { frontMatter: {}, markdown: content }
  }
  
  const frontMatterContent = match[1]
  const markdownContent = match[2]
  
  const frontMatter: Record<string, any> = {}
  frontMatterContent.split('\n').forEach(line => {
    const colonIndex = line.indexOf(':')
    if (colonIndex > 0) {
      const key = line.slice(0, colonIndex).trim()
      let value = line.slice(colonIndex + 1).trim()
      
      // 处理数组类型的值
      if (value.startsWith('[') && value.endsWith(']')) {
        const arrayValue = value.slice(1, -1).split(',').map(item => item.trim().replace(/['"]/g, ''))
        frontMatter[key] = arrayValue
      } else {
        frontMatter[key] = value
      }
    }
  })
  
  return { frontMatter, markdown: markdownContent }
}

// 加载所有博客文章
export async function loadBlogPosts(): Promise<BlogPost[]> {
  try {
    const posts: BlogPost[] = []
    
    // 手动导入所有Markdown文件
    const blogModules = import.meta.glob('../../content/blog/*.md', { 
      eager: true, 
      query: '?raw',
      import: 'default'
    })
    
    for (const [path, module] of Object.entries(blogModules)) {
      try {
        const content = (module as any).default || module
        const { frontMatter, markdown } = parseFrontMatter(content as string)
        
        const post: BlogPost = {
          id: path.split('/').pop()?.replace('.md', '') || '',
          title: frontMatter.title || 'Untitled',
          date: frontMatter.date || new Date().toISOString(),
          author: frontMatter.author || 'Unknown',
          tags: Array.isArray(frontMatter.tags) ? frontMatter.tags : [],
          summary: frontMatter.summary || '',
          content: marked.parse(markdown) as string,
          filePath: path
        }
        
        posts.push(post)
      } catch (error) {
        console.warn(`Failed to parse blog post from ${path}:`, error)
      }
    }
    
    return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  } catch (error) {
    console.error('Error loading blog posts:', error)
    return []
  }
}

// 获取博客统计信息
export function getBlogStats(posts: BlogPost[]): BlogStats {
  const tagCounts: Record<string, number> = {}
  
  posts.forEach(post => {
    post.tags.forEach(tag => {
      tagCounts[tag] = (tagCounts[tag] || 0) + 1
    })
  })
  
  return {
    totalPosts: posts.length,
    totalTags: Object.keys(tagCounts).length,
    latestPost: posts[0],
    tagCounts
  }
}

// 过滤博客文章
export function filterBlogPosts(
  posts: BlogPost[], 
  filters: { tag?: string; search?: string }
): BlogPost[] {
  return posts.filter(post => {
    // 标签过滤
    if (filters.tag && !post.tags.includes(filters.tag)) {
      return false
    }
    
    // 搜索过滤
    if (filters.search) {
      const searchTerm = filters.search.toLowerCase()
      return (
        post.title.toLowerCase().includes(searchTerm) ||
        post.summary.toLowerCase().includes(searchTerm) ||
        post.tags.some(tag => tag.toLowerCase().includes(searchTerm))
      )
    }
    
    return true
  })
}